package com.pz.cloud.framework.util;

import com.baomidou.mybatisplus.annotation.TableName;
import com.pz.cloud.framework.model.SqlQueryGenerator;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.enums.DataScope;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanConvertUtil;

import javax.persistence.Table;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * 3hmzz 业务工具类
 */
public class BizUtil {

    public static BizUtil bizUtil;
    static {
        get();
    }
    private BizUtil(){

    }

    public static LoginUser getUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser;
    }

    public static String getUserId(){
        return getUser()==null?null:getUser().getId();
    }

//    private static List<String> getPermissionCodes(String bizCode) {
//        List perCodes = new ArrayList();//权限标志[dept,all,deptTree]
//        if(StringUtils.isNotEmpty(bizCode)){
////            String scopeBizCode = bizCode+"-scope";//权限范围代码 默认加-scope
//            String scopeBizCode = bizCode;
//            Set codeList = null;
//            String url = "http://hhh-admin/sysResource/findByFullCode";
//
////            MultiValueMap map = new LinkedMultiValueMap();
////            map.add("fullCode",scopeBizCode);
////            MultiValueMap head = new LinkedMultiValueMap();
////            head.add("content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
////            Result scopeResources = RestUtil.balanceExecute(url, map,head,Result.class);
//
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("fullCode",scopeBizCode);
//            Result scopeResources = bizUtil.sysResourceClient.findByFullCode(jsonObject);
//            Result childScopeResources = null;//scope下面子对象
//            if(scopeResources!=null&&scopeResources.getData()!=null){
//                Map data = (Map) scopeResources.getData();
//                jsonObject.clear();
//                jsonObject.put("parentId",data.get("id"));
//                childScopeResources = bizUtil.sysResourceClient.findByParentId(jsonObject);
//            }
//            if(childScopeResources!=null){
//                List<Map> chils = (List)childScopeResources.getData();
//                for (Map r : chils) {
//                    if(codeList.contains(r.get("fullCode"))){
//                        perCodes.add(r.get("code").toString().substring(1));//-all -dept
//                    }
//                }
//            }
//        }
//        return perCodes;
//    }
//    private static Set<String> getCodeList(){
//        //如果是管理员用户，忽略用户角色权限限制。
//        List<UnitResourcesBean> unitResourcesBeans;
//        List<String> roleIds ;
//        roleIds = bizUtil.untiRoleService.findRoleByAccountId(ShiroUtils.getUserId());
//        List<PermissionBean> permissionBeanList = bizUtil.userCenterService.findByRoleIdInAndResType(new HashSet<>(roleIds), 1);
//        Set<String> ids = new HashSet<>();
//        permissionBeanList.forEach((e)->{
//            ids.add(e.getResId());
//        });
//        unitResourcesBeans = bizUtil.unitResourcesService.findByIdIn(ids);
//
//        Set<String> codeList = new HashSet<>();
//        unitResourcesBeans.forEach((e)-> codeList.add(e.getFullCode()));
//        return codeList;
//    }

    /**
     * 获取主键字段名
     *
     * @param entity 实体对象
     * @param <E>    实体类对应的类定义
     * @return 主键字段名
     */
    public static <E>  String getIdFieldName(E entity) {
        Class entityClass = entity.getClass();
        Field[] fields = entityClass.getDeclaredFields();

        String pkFieldName = null;
        if (fields != null) {
            for (Field field : fields) {
                if (isIdField(field)) {
                    pkFieldName = field.getName();
                    break;
                }
            }
        }

        return pkFieldName;
    }
    /**
     * 获取主键字段值
     *
     * @param entity 实体对象
     * @param <E>    实体类对应的类定义
     * @return 主键字段名
     */
    public static <E>  String getIdFieldValue(E entity){
        String value = null;
        try{
            String pkFieldName = getIdFieldName(entity);
            if(StringUtils.isNotEmpty(pkFieldName)){
                value =(String) PropertyUtils.getProperty(entity, pkFieldName);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }
    /**
     * 设置地段值
     *
     * @param entity 实体对象
     * @param <E>    实体类对应的类定义
     * @return 主键字段名
     */
    public static <E>  void setFiledValue(E entity,String filedName,Object value){
        try{
            PropertyUtils.setProperty(entity,filedName,value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 判断是否为实体的主键字段
     *
     * @param field bean的字段信息
     * @return 若为实体的主键字段，则返回true
     */
    private static boolean isIdField(Field field) {
        if(field.getName().equals("id")){
            return true;
        }

        Annotation[] fieldAnnotations = field.getDeclaredAnnotations();
        boolean isPkfield = false;
        if (fieldAnnotations != null) {
            for (Annotation fieldAnnotation : fieldAnnotations) {

                if (fieldAnnotation.annotationType().getName().equals("javax.persistence.Id")||fieldAnnotation.annotationType().getName().equals("com.baomidou.mybatisplus.annotation.TableId")) {
                    isPkfield = true;
                    break;
                }
            }
        }
        return isPkfield;
    }
    public static BizUtil get(){
        if(bizUtil==null){
           bizUtil = new BizUtil();
//           bizUtil.sysResourceClient = SpringContextUtils.getBean(SysResourceClient.class);
        }
        return bizUtil;
    }
    public static String getTableName(Class cla){
        Table table = (Table) cla.getAnnotation(Table.class);
        if(table!=null){
            return table.name();
        }else{
            TableName tableName = (TableName) cla.getAnnotation(TableName.class);
            if(tableName!=null){
                return tableName.value();
            }else{
               return BeanConvertUtil.camelToUnderline(cla.getSimpleName());
            }
        }
    }

    /**
     * 根据类名获取springBean名称
     */
    public static String getBeanName(Class cls) {
        String firstChar = cls.getSimpleName().substring(0, 1).toLowerCase();
        return firstChar+cls.getSimpleName().substring(1);
    }

    public static DataScope getDataScope(){
        DataScope dataScope = DataScope.个人;
        if(SqlQueryGenerator.hasRule(DataScope.全部.getCode())){
            dataScope =  DataScope.全部;
        }else if(SqlQueryGenerator.hasRule(DataScope.组织树.getCode())){
            dataScope =  DataScope.组织树;
        }else if(SqlQueryGenerator.hasRule(DataScope.组织.getCode())){
            dataScope = DataScope.组织;
        }
        return dataScope;
    }
}
